package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.tomcat.util.descriptor.web.ContextHandler;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
@Aspect
@Component
public class LoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;


    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(authLogin)")
    public Object loginAspect(ProceedingJoinPoint joinPoint, AuthLogin authLogin) throws Throwable {


        Object o = null;
        try {

            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            String token = servletRequestAttributes.getRequest().getHeader("token");

            String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token; // loginKey一定不为空(有前缀),故不必判空
            UserInfoVo userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(loginKey);
            if (authLogin.required() && userInfoVo == null) {
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }

            if (userInfoVo != null) {
                AuthContextHolder.setUserId(userInfoVo.getId());
                AuthContextHolder.setUsername(userInfoVo.getNickname());
            }

            o = joinPoint.proceed(); //执行目标方法

        } finally {

            AuthContextHolder.removeUserId();
            AuthContextHolder.removeUsername();

        }


        return o;
    }
}
